package com.tree;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import com.hpm.DButil;

public class PermissionService {
	public void deleteOldPermission(String adminId){
		String sql = "delete from adminnodes where id=?";
		Connection conn = null;
		PreparedStatement ps = null;
		try {
			conn = DButil.getConnection();
			ps = conn.prepareStatement(sql);
			ps.setString(1, adminId);
			ps.execute();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally{
			DButil.close(conn, ps, null);
		}
	}
	
	public void addNewPermission(String adminId, String[] nodes){
		List<String> list = new ArrayList<String>();
		for(String nodeId:nodes){
			list.add("insert into adminnodes values("+adminId+","+nodeId+")");
		}
		DButil db = new DButil();
		Object[] objs = list.toArray();
		String[] strs = new String[objs.length];
		for (int i = 0; i < objs.length; i++)
			strs[i] = (String) objs[i];
		db.updateBatch(strs);
	}
	
	public boolean hasPermission(String adminId, String nodeId) {
		String sql = "select id,nodeid from adminnodes where id='" + adminId + "' and nodeid='" + nodeId + "'";
		Connection conn = null;
		Statement st = null;
		ResultSet rs = null;
		try {
			conn = DButil.getConnection();
			st = conn.createStatement();
			rs = st.executeQuery(sql);
			while (rs.next()) {
				return true;
			}
		} catch (SQLException e) {
			e.printStackTrace();
			return false;
		} finally{
			DButil.close(conn, st, rs);
		}
		return false;
	}
	
	public boolean hasPermission(String adminId) {
		String sql = "select id,nodeid from adminnodes where id='" + adminId +"'";
		Connection conn = null;
		Statement st = null;
		ResultSet rs = null;
		try {
			conn = DButil.getConnection();
			st = conn.createStatement();
			rs = st.executeQuery(sql);
			while (rs.next()) {
				return true;
			}
		} catch (SQLException e) {
			e.printStackTrace();
			return false;
		} finally{
			DButil.close(conn, st, rs);
		}
		return false;
	}
	
	public List<String> getPermissions(String adminId) {
		String sql = "select nodeid from adminnodes where id='" + adminId +"'";
		Connection conn = null;
		Statement st = null;
		ResultSet rs = null;
		List<String> list = new ArrayList<String>();
		try {
			conn = DButil.getConnection();
			st = conn.createStatement();
			rs = st.executeQuery(sql);
			while (rs.next()) {
				list.add(rs.getString("nodeid"));
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally{
			DButil.close(conn, st, rs);
		}
		return list;
	}
}
